<?php
/**
 * Created by PhpStorm.
 * User: 李大爷
 * Date: 2019/2/26
 * Time: 15:18
 */

namespace app\controllers;

use Yii;
use yii\db\Query;
use yii\data\Pagination;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\NotFoundHttpException;

class ReportController extends BaseController
{
    /**
     * 任务统计
     * @return string|\yii\web\Response
     */
    public function actionCampaign()
    {
        if (Yii::$app->request->isAjax){
            $campaign = (new Query())->from('campaign')->orderBy('id desc')->all($this->callcenter_db);
            foreach ($campaign as &$c){
                $calls = (new Query())->from('calls')->where(['id_campaign'=>$c['id']])->all($this->callcenter_db);
                $total = $hasCall = $leftCall = $success = $failed = 0;
                $total = count($calls);
                foreach ($calls as $call){
                    if ($call['status']){
                        $hasCall += 1;
                    }
                    if ($call['status']=='Abandoned'){
                        $success += 1;
                    }
                    if ($call['status']=='Failure'){
                        $failed += 1;
                    }
                }
                //总数
                $c['total'] = $total;
                //已呼叫
                $hasCallPercent = $c['total']>0?100*round($hasCall/$c['total'],4).'%':'0%';
                $c['hasCall'] = $hasCall." [".$hasCallPercent."]";
                //剩余
                $leftCall = $c['total']-$c['hasCall'];
                $leftCallPercent = $c['total']>0?100*round($leftCall/$c['total'],4).'%':'0%';
                $c['leftCall'] = $leftCall." [".$leftCallPercent."]";
                //接通数
                $successPercent = $hasCall>0?100*round($success/$hasCall,4).'%':'0%';
                $c['success'] = $success." [".$successPercent."]";
                //转接数
                $transfer = (new Query())->from('cdr')->where(['and','userfield='.$c['id'],'dst!='.$c['queue'],'disposition="ANSWERED"'])->count("*",$this->cdr_db);
                $transferPercent = $successPercent>0?100*round($transfer/$success,4).'%':'0%';
                $c['transfer'] = $transfer." [".$transferPercent."]";
                //呼叫失败
                $failedPercent = $hasCall>0?100*round($failed/$hasCall,4).'%':'0%';
                $c['failed'] = $failed." [".$failedPercent."]";
                //状态
                $c['estatus_name'] = Yii::$app->params['estatus'][$c['estatus']];

            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => count($campaign),
                'data' => $campaign,
            ]);
        }
        return $this->render('campaign');
    }

    /**
     * 分机统计
     * @return string|\yii\web\Response
     */
    public function actionExtension()
    {
        if (Yii::$app->request->isAjax){
            $extension_where = [];
            $name = Yii::$app->request->get('name');
            if ($name){
                $extension_where['name'] = $name;
            }
            $extension = Yii::$app->request->get('extension');
            if ($extension){
                $extension_where['extension'] = $extension;
            }
            $db = (new Query())->from('users')->where($extension_where);
            $count = $db->count('*',$this->asterisk_db);
            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $extension = $db->orderBy('extension desc')
                ->offset(($page-1)*$limit)
                ->limit($limit)
                ->all($this->asterisk_db);

            $calldate = Yii::$app->request->get('calldate');
            foreach ($extension as &$e){
                //每次需要重置cdr_where条件
                $cdr_where = [];
                if ($calldate){
                    $cdr_where[] = 'and';
                    $explode = explode(' - ',$calldate);
                    $cdr_where[] = ['between','calldate',trim($explode[0]),trim($explode[1])];
                    $cdr_where[] = ['=','src',$e['extension']];
                }else{
                    $cdr_where = ['=','src',$e['extension']];
                }

                $total = (new Query())->from('cdr')->where($cdr_where)->all($this->cdr_db);
                //呼叫数
                $e['total'] = count($total);
                //30s以上通话
                $e['thirty'] = 0;
                //60s以上通话
                $e['sixty'] = 0;
                //累计时长
                $e['sum'] = 0;
                //接通数
                $e['answered'] = 0;
                foreach ($total as $t){
                    if ($t['disposition']=='ANSWERED'&&$t['billsec']>0){
                        $e['answered']++;
                    }
                    if ($t['disposition']=='ANSWERED'&&$t['billsec']>=30){
                        $e['thirty']++;
                    }
                    if ($t['disposition']=='ANSWERED'&&$t['billsec']>=60){
                        $e['sixty']++;
                    }
                    $e['sum'] += $t['billsec'];
                }
                //接通率
                $e['percent'] = $e['total']?100*round($e['answered']/$e['total'],4).'%':'0%';
                //平均时长
                $e['avg'] = $e['answered']?round($e['sum']/$e['answered'],2):0;
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $extension,
            ]);
        }
        return $this->render('extension');
    }

    /**
     * 分机监控
     * @return string|\yii\web\Response
     */
    public function actionExtensionMonitor()
    {
        if (Yii::$app->request->isAjax){
            $data = [];
            $extensions = (new Query())->from('users')->select(['extension'])->all($this->asterisk_db);
            foreach ($extensions as $e){
                $rs = $this->ami->ExtensionState($e['extension'],'from-internal');
                $data['exten'][$e['extension']] = [
                    'status' => $rs['Status'],
                    'status_name' => Yii::$app->params['extension_status'][$rs['Status']]
                ];
            }
            //总分机数
            $data['count']['total'] = count($extensions);
            //为每个状态赋初始值0
            foreach (Yii::$app->params['extension_status'] as $k=>$v){
                $data['count']['status_'.$k] = 0;
            }
            foreach ($data['exten'] as $d){
                $data['count']['status_'.$d['status']]++;
            }
            return $this->asJson(['code'=>0,'msg'=>'请求成功','data'=>$data]);
        }

        $db = (new Query())->from('users')->orderBy('extension desc');
        $total = $db->count('*',$this->asterisk_db);
        $pages = new Pagination(['totalCount'=>$total,'defaultPageSize'=>24]);
        $data = $db->offset($pages->offset)->limit($pages->limit)->all($this->asterisk_db);
        foreach ($data as &$d){
            $rs = $this->ami->ExtensionState($d['extension'],'from-internal');
            $d['status'] = $rs['Status'];
            $d['status_name'] = Yii::$app->params['extension_status'][$rs['Status']];
        }
        return $this->render('extension-monitor',['data'=>$data,'pages'=>$pages]);
    }

    /**
     * @param $master
     * @param $exten
     * @param $type
     * @return \yii\web\Response
     * 1-密语，客户听不到监听者说话 （常用）
     * 2-强插，三方正常通话
     * 3-旁听，只能听
     */
    public function actionChanspy()
    {
        $exten = Yii::$app->request->post('exten');
        $type = Yii::$app->request->post('type');

        //当前用户是否已绑定分机号
        if (!Yii::$app->user->identity->exten){
            return $this->asJson(['code'=>1,'msg'=>'未绑定分机号，请先绑定']);
        }
        $master = Yii::$app->user->identity->exten;

        //验证组装监听参数
        if (!in_array($type,[1,2,3])){
            return $this->asJson(['code'=>1,'msg'=>'监听参数错误']);
        }
        switch ($type) {
            case 1:
                $dataExt = "Ew";
                break;
            case 2:
                $dataExt = "EB";
                break;
            case 3:
                $dataExt = "E";
                break;
            default:
                $dataExt = "";
                break;
        }
        //禁止自己监听自己
        if ($master==$exten){
            return $this->asJson(['code' => 1, 'msg' => '不能监听自己分机']);
        }
        //监听分机状态，监听分机必需空闲
        $res = $this->ami->ExtensionState($master,'from-internal');
        if ($res['Status'] != 0) {
            return $this->asJson(['code' => 1, 'msg' => '分机：' . $master . '不在空闲状态']);
        }
        //被监听分机状态，被监听分机必需在通话中
        $res = $this->ami->ExtensionState($exten,'from-internal');
        if ($res['Status'] != 1) {
            return $this->asJson(['code' => 1, 'msg' => '分机：' . $exten . '不在通话中']);
        }
        //发起监听
        $data = "SIP/" . $exten . "," . $dataExt;
        $res = $this->ami->Originate("SIP/" . $master, $exten, 'from-internal', 1, "ChanSpy", $data, null, $master, null, null, true);
        if ($res['Response'] != 'Error') {
            return $this->asJson(['code' => 0, 'msg' => '已发送监听请求，请注意接听来电', 'data' => $res]);
        }
        return $this->asJson(['code' => 1, 'msg' => '监听失败', 'data' => $res]);

    }

}